package com.shqcjd.sinopecdemomobile.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.shqcjd.sinopecdemomobile.R;
import com.shqcjd.sinopecdemomobile.api.ApiService;
import com.shqcjd.sinopecdemomobile.app.AppConstant;
import com.shqcjd.sinopecdemomobile.app.MyApp;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.sinopecdemomobile.model.ResponseData;
import com.shqcjd.sinopecdemomobile.model.pojo.InspectionListBean;
import com.shqcjd.sinopecdemomobile.model.pojo.QRScanBean;
import com.shqcjd.sinopecdemomobile.model.pojo.TaskCodeBean;
import com.shqcjd.sinopecdemomobile.ui.adapter.IntellectInspectionAdapter;
import com.shqcjd.sinopecdemomobile.ui.base.BaseActivity;
import com.shqcjd.sinopecdemomobile.ui.base.BasePresenter;
import com.shqcjd.sinopecdemomobile.util.Config;
import com.shqcjd.sinopecdemomobile.util.PrefUtils;
import com.shqcjd.sinopecdemomobile.util.WrapContentLinearLayoutManager;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

public class IntellectInspectActivity extends BaseActivity {

    @BindView(R.id.tv_include_title)
    TextView tvIncludeTitle;
    @BindView(R.id.tv_include_finish)
    Button tvIncludeFinish;
    @BindView(R.id.et_intellect_manage)
    EditText etIntellectManage;
    @BindView(R.id.rv_intellect_back)
    RecyclerView rvIntellectBack;
    @BindView(R.id.sr_intellect_back)
    SwipeRefreshLayout srIntellectBack;
    @BindView(R.id.rl_isnull)
    RelativeLayout rlIsnull;

    private Context context;
    private IntellectInspectionAdapter intellectInspectionAdapter;
    private List<InspectionListBean.ListBean> adapterList = new ArrayList<>();
    private int page = 1;
    private int isRefreshOrLoadMore = 0;//0代表刷新  1代表加载更多
    private int total;
    private String strSearch;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_intellect_inspect;
    }

    @Override
    public void init() {
        super.init();
        context = this;
    }

    @Override
    public void initView() {
        super.initView();
        tvIncludeTitle.setText("智能巡检");

        tvIncludeFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        srIntellectBack.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });

        etIntellectManage.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                strSearch = s.toString();
                refreshData();
            }
        });

        refreshData();
    }

    private void refreshData() {
        refreshOrLoadMore();
        srIntellectBack.setRefreshing(true);
        isRefreshOrLoadMore = 0;
        page = 1;
        adapterList.clear();
        getData(page);
    }

    private void loadMoreData() {
        isRefreshOrLoadMore = 1;
        getData(page + 1);
    }

    private void refreshOrLoadMore() {
        if (intellectInspectionAdapter != null) {
            intellectInspectionAdapter.notifyLoadMoreToLoading();
        }
    }

    private void getData(int p) {
        Map<String, String> map = new HashMap<>();
        map.put("pageIndex",p+"");
        map.put("pageSize",Config.PAGE_TOTAL+"");
        map.put("state",1+"");//1待巡检  2已巡检
        map.put("searchContent",strSearch);

        ApiService.getInspectionList(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<InspectionListBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
//                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<InspectionListBean> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            total = retData.data.total;
                            adapterList.addAll(retData.data.list);
                            if (intellectInspectionAdapter == null) {
                                rvIntellectBack.setLayoutManager(new WrapContentLinearLayoutManager(context));
                                intellectInspectionAdapter = new IntellectInspectionAdapter(adapterList);
                                rvIntellectBack.setAdapter(intellectInspectionAdapter);

                                intellectInspectionAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                                    @Override
                                    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                                        InspectionListBean.ListBean item = (InspectionListBean.ListBean) adapter.getItem(position);
                                        Intent intent;
                                        switch (view.getId()) {
                                            case R.id.tv_generate_qr://生成二维码
                                                TaskCodeBean taskCodeBean = new TaskCodeBean();
                                                taskCodeBean.user_id = item.user_id;
                                                taskCodeBean.task_id = item.taskId;
                                                QRScanBean bean = new QRScanBean();
                                                Gson gson = new Gson();
                                                bean.json = gson.toJson(taskCodeBean);
                                                bean.sceneType =3;
                                                bean.token = PrefUtils.getString(MyApp.getmContext(), AppConstant.TOKEN_KEY, "-1");
                                                String json = gson.toJson(bean);

                                                intent = new Intent(context, GenerateQRcodeActivity.class);
                                                intent.putExtra("QRcode",json);
                                                startActivity(intent);
                                                break;
                                            case R.id.tv_start_inspection://开始巡检
                                                intent = new Intent(context,InspectionTaskActivity.class);
                                                intent.putExtra("taskId",item.taskId);
                                                startActivity(intent);
                                                break;
                                            case R.id.tv_file_btn://文件列表
                                                intent = new Intent(context, FileListActivity.class);
                                                intent.putExtra("taskId", item.taskId);
                                                startActivity(intent);
                                                break;
                                        }
                                    }
                                });
                                intellectInspectionAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                                    @Override
                                    public void onLoadMoreRequested() {
                                        int pageSize = total % Config.PAGE_TOTAL == 0 ? total / Config.PAGE_TOTAL : total / Config.PAGE_TOTAL + 1;
                                        if (page >= pageSize) {
                                            rvIntellectBack.post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    intellectInspectionAdapter.loadMoreEnd();
                                                }
                                            });
                                        } else {
                                            loadMoreData();
                                        }
                                    }
                                });
                            }
                            if (isRefreshOrLoadMore == 1) {
                                page = page + 1;
                                intellectInspectionAdapter.loadMoreComplete();
                            }
                            if(adapterList.size()>0){
                                rlIsnull.setVisibility(View.GONE);
                            }else{
                                rlIsnull.setVisibility(View.VISIBLE);
                            }
                            intellectInspectionAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        srIntellectBack.setRefreshing(false);
                    }
                });
    }


}
